<?php

/**
 * This file is part of Webman AI.
 *
 * @author    walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link      http://www.workerman.net/
 */

namespace plugin\ai\app\handler;

use plugin\ai\app\model\AiModel;
use ReflectionClass;

/**
 * Class Base
 */
Class Base
{
    /**
     * 模型处理器名称
     * @var string
     */
    protected static $name = '';

    /**
     * @var string 模型类型
     */
    protected static $type = '';

    /**
     * @var int 优先级，数值越大优先级越高
     */
    protected static $priority = 0;

    /**
     * 支持的模型列表
     * @var array
     */
    public static $models = [];

    /**
     * 自定义配置
     * @var array
     */
    public static $defaultSettings = [];

    /**
     * @var bool
     */
    protected static $balanceVisible = false;

    /**
     * @var mixed
     */
    protected $driver;

    /**
     * @var string 处理器
     */
    protected $driverClass = null;

    /**
     * @var array
     */
    protected $settings = [];

    /**
     * @param array $settings
     */
    public function __construct(array $settings = [])
    {
        $this->settings = $settings;
    }

    /**
     * 初始化模型处理器
     * @return void
     */
    public static function init()
    {
        if (!AiModel::where('handler', static::getClassName())->first()) {
            $model = new AiModel();
            $model->name = static::$name;
            $model->type = static::$type;
            $model->handler = static::getClassName();
            $model->models = implode("\n", static::$models);
            $model->priority = static::$priority;
            $model->balance_visible = (int)static::$balanceVisible;
            $settings = static::$defaultSettings;
            $model->settings = json_encode($settings, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
            $model->save();
        }
    }

    /**
     * 从数据库中获取配置
     * @return array
     */
    public function getSettings()
    {
        return $this->settings;
    }

    /**
     * 获取模型处理器名称
     * @param bool $shortName
     * @return string
     */
    public static function getClassName(bool $shortName = false): string
    {
        if ($shortName) {
            return (new ReflectionClass(get_called_class()))->getShortName();
        }
        return get_called_class();
    }

}